package mume.android;

import java.util.Vector;

import mume.infoRetriever.AsinInfoRetriever;
import mume.infoRetriever.ImageGetterImp;
import mume.music.Mp3Player;
import mume.music.Mp3Scraper;
import mume.scanning.ASINfinder;
import mume.scanning.BarcodeImageConverter;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;

public class MainActivity extends TabActivity implements OnClickListener, OnItemSelectedListener{

	private static final int MENU_NEW_GAME = 0;
	private static final int MENU_QUIT = 1;
	
	private TabHost mTabHost;
	private ListView musicList;
	private int selectedItem;
	
	private Mp3Scraper scrap;
	private Mp3Player player;
	private AsinInfoRetriever asinRet;
	
	private CaptureWindow captureWindow;
	
   @Override
   public void onCreate(Bundle savedInstanceState) {
	   super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       
       scrap = new Mp3Scraper(this);
       player = new Mp3Player(this);
       asinRet = new AsinInfoRetriever();
       
       mTabHost = getTabHost();
       initTab1();
       initTab2();
       initTab3();
       initTab4();
       mTabHost.setCurrentTab(0);

   }
   
   /* set tab 1 */
   public void initTab1(){
	   mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Scan CD").setContent(R.id.tab1));
	   captureWindow = new CaptureWindow(this);       
   }
   
   /* set tab 2 */
   public void initTab2(){
	   mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Artist").setContent(R.id.ArtistLayout));
   }

   /* set tab 3 */
   public void initTab3(){
	   mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("Album").setContent(R.id.AlbumLayout));
   }
   
   /* set tab 3 */
   public void initTab4(){
		mTabHost.addTab(mTabHost.newTabSpec("tab_test4").setIndicator("Songs").setContent(R.id.TracksLayout));

		musicList = (ListView) findViewById(R.id.musicList);
		musicList.setOnItemSelectedListener(this);
		selectedItem = 0;
		
		Button play = (Button) findViewById(R.id.Play);
		play.setOnClickListener(this);
		Button stop = (Button) findViewById(R.id.Stop);
		stop.setOnClickListener(this);
   }
   
   /* Creates the menu items */
   public boolean onCreateOptionsMenu(Menu menu) {
	   	MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.options_menu, menu);
	    return true;
   }
   
   /* Handles item selections */
   public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_NEW_GAME:
           mTabHost.setCurrentTab(0);
           
           return true;
       case MENU_QUIT:
    	   this.onDestroy();
           this.finish();
           return true;
       }
       return false;
   }
   
   private String getBarcode(){
	   Reader reader = new MultiFormatReader();
	   Result result = null;
	   Bitmap bitmap = BitmapFactory.decodeResource(getResources(),captureWindow.getImage());
	   BarcodeImageConverter source = new BarcodeImageConverter(bitmap);
	   try {
		   result = reader.decode(source);
		   return result.getText();
	   } catch (ReaderException e) {
		   showDialog("error", "cannot read barcode");
		   return null;
	   }

   }

	private void showDialog(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("OK", null);
		builder.show();
	}
   
   private void scrapeSongs(String album, String artist){
       String albumsToText = "";
       album = album.replace(' ', '-');
       artist = artist.replace(' ','-');
       album = album.toLowerCase();
       artist = artist.toLowerCase();
       
       Vector<String> albumSongs = scrap.getMp3List(artist, album);
       
       if(albumSongs != null){
       		albumsToText += "Songs:\n";
	        for(int i = 0; i < albumSongs.size(); ++i){
	        	albumsToText += (albumSongs.get(i) + "\n");
	        }
	        player.setPlayList(albumSongs);
       }	
   }
   
   public void useBarcode()
   {
		ASINfinder asinFinder = new ASINfinder(this);
		String getBarcode = getBarcode();
		String info = "";
		
		if(getBarcode != null){
			info += asinFinder.getASIN(getBarcode);
			asinRet.retrieveInfo(asinFinder.getASIN(getBarcode));
			fillData();
			
			String album = asinRet.getAlbum();
			String artist = asinRet.getArtist();
			scrapeSongs(album,artist);			
		}else{
			;
		}   
   }
	
	public void fillData()
	{
		ImageGetterImp getter = new ImageGetterImp();
	    int num;
	    String info;
	    TextView tvAr0 = (TextView) findViewById(R.id.ArtistName);
	    TextView tvAr1 = (TextView) findViewById(R.id.ArtistTextViewRight);
	    TextView tvAr2 = (TextView) findViewById(R.id.ArtistTextViewBottom);
	    ImageView ivAr = (ImageView) findViewById(R.id.ArtistImageView);

		info = Html.fromHtml(asinRet.getArtistInfo()).toString();
		num = info.indexOf(' ', 185);
		tvAr0.setText(asinRet.getArtist());
		if(num != 0) {
			tvAr1.setText(info.substring(0, num+1));
			tvAr2.setText(info.substring(num+1));
		} else {
			tvAr1.setText(info);
			tvAr2.setText("");
		}
		ivAr.setImageDrawable(getter.getDrawable(asinRet.getArtistImage()));

		TextView tvAl0 = (TextView) findViewById(R.id.AlbumName);
		TextView tvAl1 = (TextView) findViewById(R.id.AlbumTextViewRight);
		TextView tvAl2 = (TextView) findViewById(R.id.AlbumTextViewBottom);
		ImageView ivAl = (ImageView) findViewById(R.id.AlbumImageView);
	    
		String info2 = Html.fromHtml(asinRet.getAlbumInfo()).toString();
		
		num = info2.indexOf(' ', 185);
		tvAl0.setText(asinRet.getAlbum());
		
		if(num != 0) {
			tvAl1.setText(info2.substring(0, num+1));
			tvAl2.setText(info2.substring(num+1));
		} else {
			tvAl1.setText(info2);
			tvAl2.setText("");
		}				
		ivAl.setImageDrawable(getter.getDrawable(asinRet.getAlbumImage()));
		
		String[] array = new String[asinRet.getNumberOfTracks()];
		asinRet.getTrackList().toArray(array);
	 	musicList.setAdapter( new ArrayAdapter<String>(this,
	 		          android.R.layout.simple_list_item_1,array) );
	 	musicList.setTextFilterEnabled(true);
		musicList.setSelection(1);
	}

	public void onClick(View v) {
		if (v.getId() == R.id.Play){
			if(selectedItem > 0)
				player.playSong(selectedItem);
		}
		if( v.getId() == R.id.Stop){
			player.stopSong();
		}
	}

	public void onItemSelected(AdapterView<?> list, View view, int pos,
			long id) {
		selectedItem = list.getSelectedItemPosition();
	}

	public void onNothingSelected(AdapterView<?> arg0) {
	}
}